<template>
    <div>
        <Modal v-model="isShowModal" :title="title" @on-cancel="hide('formValidate')" :mask-closable="false" fullscreen>

            <Form ref="formValidate" :model="params" :rules="ruleValidate" label-position="top">
                <FormItem label="商品名称：" prop="goodsName">
                    <Input v-model.trim="params.goodsName" placeholder="请输入商品名称"></Input>
                </FormItem>
                <FormItem label="商品首图：" prop="thumbnail">
                    <Input v-model="params.thumbnail" disabled>
                        <div slot="prepend">
                            <Upload :action="action" :headers="headers" :show-upload-list="false" name="file"
                                    :on-success="uploadFirstSuccess">
                                <Button icon="ios-cloud-upload-outline">上传图片</Button>
                            </Upload>
                        </div>
                    </Input>
                    <Alert show-icon closable style="margin-top:10px">建议上传600x600像素的图片，大小不超过500kb</Alert>
                </FormItem>
                <FormItem label="市场价：" prop="purchasePrice">
                    <Input v-model.trim="params.purchasePrice" placeholder="请输入商品市场价" type="number"></Input>
                </FormItem>
                <FormItem label="售价：" prop="price">
                    <Input v-model.trim="params.price" placeholder="请输入商品售价" type="number"></Input>
                </FormItem>
                <FormItem label="知豆：" prop="integral">
                    <Input v-model.trim="params.integral" placeholder="请输入商品赠送知豆" type="number"></Input>
                </FormItem>
                <FormItem label="商品规格：" prop="isSku">
                    <RadioGroup v-model="params.isSku" type="button" @on-change="isSkuChange">
                        <Radio label="0">无规格</Radio>
                        <Radio label="1">有规格</Radio>
                    </RadioGroup>
                    <Button style="margin-left: 10px" v-if="isShowIsSkuBtn" @click="showSku">添加规格（{{this.params.goodsSkuList.length}}）
                    </Button>
                </FormItem>
                <FormItem label="运费规则：" prop="freightRule">
                    <RadioGroup v-model="params.freightRule" type="button" @on-change="freightRuleChange">
                        <Radio label="1">固定运费</Radio>
                        <Radio label="2">运费模板</Radio>
                    </RadioGroup>
                    <Input v-if="isShowFreightPrice" v-model.trim="params.freightPrice" placeholder="运费价格" type="number"
                           style="width: 130px;margin-left: 10px"></Input>
                    <Select v-if="isShowFreightId" v-model="params.freightId" placeholder="选择模板"
                            style="width: 180px; margin-left: 10px" @on-change="freightIdChange">
                        <Option v-for="(item,index) in freightList" :value="item.freightId" :key="index">
                            {{item.freightName}}
                        </Option>
                    </Select>
                </FormItem>
                <FormItem label="商品组图：" prop="goodsImages">
                    <div class="hs-upload-image-box">
                        <Upload ref="goodsGroup" :action="action" :headers="headers" :show-upload-list="false"
                                name="file" multiple
                                :on-success="uploadImagesSuccess"
                                :default-file-list="defaultFileList">
                            <div class="hs-upload-add">
                                <Icon type="md-add" size="30"/>
                            </div>
                        </Upload>
                        <div class="hs-upload-image" v-for="(item,index) in params.goodsImagesList">
                            <template v-if="item.status === 'finished'">
                                <img :src="item.response.data">
                                <!--删除图片-->
                                <div class="hs-upload-image-delete" @click="delImage(index)">
                                    <Icon type="md-close"/>
                                </div>
                            </template>
                            <template v-else>
                                <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
                            </template>
                        </div>
                    </div>
                    <Alert show-icon closable style="margin-top:10px">建议上传600x600像素的图片，大小不超过500kb</Alert>
                </FormItem>
                <FormItem label="商品详情：" prop="goodsInfo">
                    <hs-edit ref="edit" id="0" v-if="isEditShow" :value="params.goodsInfo"
                             @edit-out="editOut"></hs-edit>
                </FormItem>
            </Form>

            <!-- 重写对话框底部按钮 -->
            <div slot="footer">
                <Button @click="hide('formValidate')">取消</Button>
                <Button v-if="type != 1" type="primary" @click="handleSubmit('formValidate')" :loading="loadingBtn">
                    <span v-if="!loadingBtn">确定</span>
                    <span v-else>请稍候...</span>
                </Button>
            </div>
        </Modal>

        <!-- 商品规格设置 -->
        <goods-sku-ope ref="goodsSkuOpe" :specGroup="params.specGroup" :goodsSkuList="params.goodsSkuList" @skuEditDone="skuEditDone"></goods-sku-ope>
    </div>
</template>

<script>
    import hsEdit from '@/components/hs-edit';
    import goodsSkuOpe from './goods-sku-ope';

    export default {
        name: "goods-ope",
        props:['freightList'],
        data() {
            return {
                isShowModal: false,
                isEditShow: false,
                isShowIsSkuBtn: false,
                isShowFreightPrice: true,
                isShowFreightId: false,
                loadingBtn: false,
                title: '查看信息',
                goodsTypeValue: [],
                defaultFileList: [],
                type: 0,
                action: this.$uploadURL,
                headers: {
                    token: JSON.parse(sessionStorage.getItem('J-TOKEN')).token
                },
                params: {
                    goodsMallId: '',
                    goodsName: '',
                    thumbnail: '',
                    goodsTypeIdA: '',
                    goodsTypeIdB: '',
                    freightRule: '1',
                    freightPrice: '',
                    freightId: '',
                    goodsInfo: '',
                    goodsImages: '',
                    goodsImagesList: [],
                    purchasePrice: '',
                    price: '',
                    integral: '',
                    isSku: '0',
                    isUpShelf: '2',
                    specGroup: [],
                    goodsSkuList: [],
                },
                ruleValidate: {
                    goodsName: [
                        {required: true, message: '商品名称不能为空', trigger: 'change'}
                    ],
                    thumbnail: [
                        {required: true, message: '商品首图不能为空', trigger: 'change'}
                    ],
                    goodsTypeIdA: [
                        {required: true, message: '请选择商品分类', trigger: 'change', type: 'number'}
                    ],
                    purchasePrice: [
                        {required: true, message: '市场价不能为空', trigger: 'change'}
                    ],
                    price: [
                        {required: true, message: '售价不能为空', trigger: 'change'}
                    ],
                    freightRule: [
                        {required: true, message: '运费规则不能为空', trigger: 'change'}
                    ],
                    isSku: [
                        {required: true, message: '规格不能为空', trigger: 'change'}
                    ],
                    goodsInfo: [
                        {required: true, message: '商品详情不能为空', trigger: 'change'}
                    ],
                    goodsImages: [
                        {required: true, message: '商品组图不能为空', trigger: 'change'}
                    ],
                    integral: [
                        {required: true, message: '赠送的知豆不能为空', trigger: 'change'}
                    ]
                }
            }
        },
        mounted() {
        },
        methods: {
            // 点击提交验证
            handleSubmit(name) {
                // console.log(this.params);
                // 判断商品二级和三级分类
                if (!this.params.goodsTypeIdB ) {
                    this.$Message.error('请选择商品二级分类');
                    return false
                }

                // 判断有规格的情况
                if (this.params.isSku == '1' && !this.params.goodsSkuList.length) {
                    this.$Message.error('请填写商品规格信息');
                    return false
                }
                // 判断运费规则
                if (this.params.freightRule == '1' && !this.params.freightPrice) {
                    this.$Message.error('请填写固定运费');
                    return false
                }
                // 判断运费规则
                if (this.params.freightRule == '2' && !this.params.freightId) {
                    this.$Message.error('请选择运费模板');
                    return false
                }

                this.$refs[name].validate((valid) => {
                    if (valid) {
                        // this.$Message.error('验证通过');
                        /**
                         * type判断
                         * 1.查看 2.新增 3.编辑
                         */
                        switch (this.type) {
                            case 1:
                                // this.title = '查看商品';
                                break;
                            case 2:
                                // 新增商品
                                this.addGoods();
                                break;
                            case 3:
                                // 编辑商品
                                this.updateGoods();
                                break;
                            default:
                                this.$Notice.error({
                                    title: '商品管理',
                                    desc: '查看，新增，编辑区分判断报错',
                                    duration: 0
                                });
                                break
                        }
                    } else {
                        this.$Message.error('还有信息没有填写合格哦~');
                    }
                })
            },
            // 显示模态框
            show(type, row) {
                this.isShowModal = true;
                this.isEditShow = true;
                this.type = type;
                /**
                 * type判断
                 * 1.查看 2.新增 3.编辑
                 */
                switch (type) {
                    case 1:
                        this.title = '查看商品';
                        this.findInfo(row);
                        break;
                    case 2:
                        this.title = '新增商品';
                        this.freightRuleChange(1);
                        this.isSkuChange(0);
                        break;
                    case 3:
                        this.title = '编辑商品';
                        this.findInfo(row);
                        break;
                    default:
                        this.$Notice.error({
                            title: '商品管理',
                            desc: '查看，新增，编辑模态框报错',
                            duration: 0
                        });
                        break
                }
            },
            // 新增商品
            addGoods() {
                this.$Spin.show();
                this.axios.post('/goodsMall/addGoods', this.params).then(res => {
                    console.log(res);
                    setTimeout(() => {
                        this.$Spin.hide();
                    }, 300);
                    if (res.status == 200) {
                        this.$emit('changeDate');
                        this.$Message.success('操作成功.');
                        this.hide('formValidate');
                    }
                    if (res.status == 201) {
                        this.$Message.error(res.msg);
                    }
                    if (res.status == 500) {
                        this.$Notice.error({
                            title: '服务器内部错误',
                            desc: '新增商品接口报错',
                            duration: 0
                        });
                    }
                })
            },
            // 编辑商品
            updateGoods() {
                this.$Spin.show();
                this.axios.post('/goodsMall/updateGoods', this.params).then(res => {
                    console.log(res);
                    setTimeout(() => {
                        this.$Spin.hide();
                    }, 300);
                    if (res.status == 200) {
                        this.$emit('changeDate');
                        this.$Message.success('操作成功.');
                        this.hide('formValidate');
                    }
                    if (res.status == 201) {
                        this.$Message.error(res.msg);
                    }
                    if (res.status == 500) {
                        this.$Notice.error({
                            title: '服务器内部错误',
                            desc: '编辑商品接口报错',
                            duration: 0
                        });
                    }
                })
            },
            // 查询商品详情
            findInfo(row) {
                this.$Spin.show();
                this.axios.post('/goodsMall/findInfo', {
                    goodsMallId: row.goodsMallId
                }).then(res => {
                    console.log(res);
                    setTimeout(() => {
                        this.$Spin.hide();
                    }, 300);
                    if (res.status == 200) {
                        // this.$Message.success('操作成功.');
                        this.params.goodsMallId = res.data.goodsMall.goodsMallId;
                        this.params.goodsName = res.data.goodsMall.goodsName;
                        this.params.goodsTypeIdA = res.data.goodsMall.goodsTypeIdA;
                        this.params.goodsTypeIdB = res.data.goodsMall.goodsTypeIdB;
                        this.params.freightRule = res.data.goodsMall.freightRule.toString();
                        this.params.freightPrice = res.data.goodsMall.freightPrice;
                        this.params.goodsInfo = res.data.goodsMall.goodsInfo;
                        this.params.goodsImages = res.data.goodsMall.goodsImages;
                        this.params.purchasePrice = res.data.goodsMall.purchasePrice.toString();
                        this.params.price = res.data.goodsMall.price.toString();
                        this.params.integral = res.data.goodsMall.integral.toString();
                        this.params.isSku = res.data.goodsMall.isSku.toString();
                        this.params.isUpShelf = res.data.goodsMall.isUpShelf;
                        this.params.goodsSkuList = res.data.goodsMallSku;
                        this.goodsTypeValue = [res.data.goodsMall.goodsTypeIdA, res.data.goodsMall.goodsTypeIdB]
                        this.params.freightId = res.data.goodsMall.freightId;

                        this.params.specGroup = res.data.goodsMall.specGroup

                        this.freightRuleChange(this.params.freightRule);

                        if(res.data.goodsMall.specGroup){
                            let arr = [];
                            res.data.goodsMallSku.forEach(v => {
                                let obj = {};
                                let specNameArr = v.specName.split(",");
                                let specValArr = v.specValue.split(",");
                                specNameArr.forEach((val, key) => {
                                    obj[val] = specValArr[key];
                                });
                                arr.push(obj);
                            });
                            // console.log(arr)
                            this.params.specGroup = arr;
                        }


                        this.isSkuChange(this.params.isSku);

                        if(res.data.goodsMall.goodsImages){
                            let goodsImages = JSON.parse(res.data.goodsMall.goodsImages);
                            // 回显图片组
                            for (let i in goodsImages) {
                                if (i == 0) {
                                    // 回显缩略图
                                    this.params.thumbnail = goodsImages[i];
                                } else {
                                    // 上传组件默认图片
                                    this.defaultFileList.push({
                                        response: {
                                            data: goodsImages[i]
                                        }
                                    });
                                    // 回显图片组
                                    this.params.goodsImagesList.push({
                                        percentage: 100,
                                        status: 'finished',
                                        showProgress: false,
                                        response: {
                                            data: goodsImages[i]
                                        }
                                    });
                                }
                            }
                        }

                    }
                    if (res.status == 500) {
                        this.$Notice.error({
                            title: '服务器内部错误',
                            desc: '查看商品详情接口报错',
                            duration: 0
                        });
                    }
                })
            },
            // 显示规格
            showSku(){
                this.$refs.goodsSkuOpe.show();
            },
            // 编辑规格之后返回的数据
            skuEditDone(e){
                // console.log(e)
                this.params.specGroup = JSON.stringify(e.specGroup);
                this.params.goodsSkuList = e.goodsSkuList;
            },
            // 富文本编辑器返回的内容
            editOut(e) {
                this.params.goodsInfo = e;
            },
            // 商品分类改变
            goodsTypeChange(e) {
                this.params.goodsTypeIdA = e[0];
                this.params.goodsTypeIdB = e[1];
            },
            // 运费模板改变
            freightIdChange(e){
                // console.log(e)
                this.params.freightId = e;
            },
            // 选择运费规则
            freightRuleChange(e) {
                // 固定运费
                if (e == '1') {
                    this.isShowFreightPrice = true;
                    this.isShowFreightId = false;
                }
                // 模板运费
                if (e == '2') {
                    this.isShowFreightPrice = false;
                    this.isShowFreightId = true;
                }
            },
            // 选择有规格或者无规格
            isSkuChange(e) {
                // 无规格
                if (e == '0') {
                    this.params.specGroup = '';
                    this.params.goodsSkuList = [];
                    this.isShowIsSkuBtn = false;
                }
                // 有规格
                if (e == '1') {
                    this.isShowIsSkuBtn = true;
                }
            },
            // 商品首图上传成功
            uploadFirstSuccess(response, file, fileList) {
                if (response.status == 200) {
                    this.params.thumbnail = response.data;
                    this.formatImagePath();
                }
                if (response.status == 201) {
                    this.$Message.error(response.msg);
                }
                if (response.status == 500) {
                    this.$Notice.error({
                        title: '服务器内部错误',
                        desc: '上传图片首图接口报错',
                        duration: 0
                    });
                }
            },
            // 商品组图
            uploadImagesSuccess(response, file, fileList) {
                if (response.status == 200) {
                    this.params.goodsImagesList = fileList;
                    this.formatImagePath();
                }
                if (response.status == 201) {
                    this.$Message.error(response.msg);
                }
                if (response.status == 500) {
                    this.$Notice.error({
                        title: '服务器内部错误',
                        desc: '上传商品组图接口报错',
                        duration: 0
                    });
                }
            },
            // 删除图片
            delImage(index) {
                const fileList = this.$refs.goodsGroup.fileList;
                fileList.splice(index, 1);
                this.params.goodsImagesList = fileList;
                this.formatImagePath();
            },
            // 格式化图片参数格式
            formatImagePath() {
                let arr = [];
                for (let i in this.params.goodsImagesList) {
                    if (this.params.goodsImagesList[i].response) {
                        arr.push(this.params.goodsImagesList[i].response.data);
                    }
                }
                // 判断有没有缩略图，如果有放在第一个位置并标识为首图
                if (this.params.thumbnail) {
                    arr.unshift(this.params.thumbnail);
                }
                // 将图片的值赋值给参数
                this.params.goodsImages = JSON.stringify(arr);
            },
            // 关闭模态框
            hide(name) {
                this.isShowModal = false;
                this.isEditShow = false;
                this.params.freightId = '';
                this.goodsTypeValue = [];
                this.params.goodsImagesList = [];
                this.params.specGroup = {};
                this.params.goodsSkuList = [];
                this.params.freightPrice = '';
                // 清空图片组上传的fileList
                this.$refs.goodsGroup.clearFiles();
                this.defaultFileList = [];
                this.$refs[name].resetFields();
            }
        },
        components: {
            hsEdit,
            goodsSkuOpe
        }
    }
</script>

<style scoped lang="less">
    .hs-upload-image-box {
        display: flex;
        align-items: center;
        position: relative;

        .hs-upload-image {
            width: 145px;
            height: 145px;
            margin-top: -8px;
            margin-left: 10px;
            border: 1px solid #efefef;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;

            .hs-upload-image-delete {
                position: absolute;
                top: -8px;
                right: -8px;
                width: 20px;
                height: 20px;
                background-color: red;
                display: flex;
                align-items: center;
                justify-content: center;
                color: #ffffff;
                border-radius: 50%;
            }

            .hs-upload-image-setting {
                position: absolute;
                bottom: 0;
                width: 100%;
                color: #ffffff;
                height: 40px;
                display: none;
                align-items: center;
                justify-content: center;
                background-color: rgba(0, 0, 0, .8);
            }

            img {
                width: 100%;
                height: 100%;
            }
        }

        .hs-upload-add {
            cursor: pointer;
            width: 145px;
            height: 145px;
            display: flex;
            align-items: center;
            justify-content: center;
            border: 1px dashed #cccccc;
            transition: all .3s;

            &:hover {
                color: #2d8cf0;
                border: 1px dashed #2d8cf0;
            }
        }
    }
</style>